package upload

import (
	"context"
	"github.com/tencentyun/cos-go-sdk-v5"
	"github.com/vueadmin/global"
	"mime/multipart"
	"net/http"
	"net/url"
	"strings"
)

var TencentOss = new(tencent)

type tencent struct{}

// 上传
func (p tencent) Upload(file *multipart.FileHeader, key string) string {
	client := p.NewClient()
	f, openError := file.Open()
	if openError != nil {
		panic(openError)
	}
	defer f.Close()

	_, err := client.Object.Put(context.Background(), strings.TrimLeft(key, "/"), f, nil)
	if err != nil {
		panic(err)
	}
	return global.CONF.TencentCOS.Schema + "://" + global.CONF.TencentCOS.Bucket + "." + "cos." + global.CONF.TencentCOS.Region + ".myqcloud.com" + key
}

// 删除
func (p tencent) DeleteFile(key string) error {
	client := p.NewClient()
	name := strings.TrimLeft(key, "/")
	_, err := client.Object.Delete(context.Background(), name)
	if err != nil {
		panic(err)
	}
	return nil
}

// 获取链接
func (p tencent) NewClient() *cos.Client {
	urlStr, _ := url.Parse(global.CONF.TencentCOS.Schema + "://" + global.CONF.TencentCOS.Bucket + ".cos." + global.CONF.TencentCOS.Region + ".myqcloud.com")
	baseURL := &cos.BaseURL{BucketURL: urlStr}
	client := cos.NewClient(baseURL, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  global.CONF.TencentCOS.SecretID,
			SecretKey: global.CONF.TencentCOS.SecretKey,
		},
	})
	return client
}
